<template>
  <div id="content" :style="{height:contentHeight+'px'}">
    <Card id="file-loading-btn" class="r-n-fs-c">
      <Button class="filter-item" @click="fileAnalyseOperator" type="primary" style="width: 100px;">文件分析</Button>
      <Button class="filter-item" @click="fileCleanOperator" type="warning" disabled style="width: 100px;">文件清理</Button>
      <Button class="filter-item r-n-c-c" style="width: 30px;position: relative;" v-if="btnLoading">
        <Spin relative class="demo-spin-col">
          <Tooltip placement="top" content="清理中">
            <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
          </Tooltip>
        </Spin>
      </Button>
    </Card>
    <Divider/>
    <Table id="card-list-info-table" class="table" stripe
           border
           show-header
           highlight-row
           :loading="isLoading"
           :columns="tableColumns"
           :data="dataList">
    </Table>
    <Divider/>
    <Card style="margin-bottom: 15px;">
      <Page class="r-w-c-c"
            class-name="card-list-info-page"
            style="width: 100%"
            :total="page.total"
            :current="page.pageNum"
            :page-size="page.pageSize"
            @on-change="onPageChange"
            @on-page-size-change="onPageSizeChange"
            show-elevator
            show-sizer
            show-total/>
    </Card>
    <Modal width="800" footer-hide v-model="isFileAnalyseModalShow" :title="modalTitle">
      <div style="margin-left: 0;width: 100%;">
        <div class="r-n-fs-c item-input">
          <span class="item-key">文件总数</span>
          <div class="item-value">{{fileAnalyseResult.total}}</div>
          <span class="item-key">文件正常在使用数</span>
          <div class="item-value">{{fileAnalyseResult.available}}</div>
          <span class="item-key">文件未使用数</span>
          <div class="item-value">{{fileAnalyseResult.unused}}</div>
          <span class="item-key">文件在使用不存在数</span>
          <div class="item-value">{{fileAnalyseResult.usedNonExistent}}</div>
        </div>
        <Table class="table" stripe
               border
               show-header
               highlight-row
               :loading="isLoading"
               :columns="fileAnalyseCategoryColumns"
               :data="fileAnalyseCategoryList">
        </Table>
      </div>
      <div slot="footer" style="display: none"></div>
    </Modal>
    <Modal v-model="modalTip" width="360">
      <p slot="header" style="color:#f60;text-align:center">
        <Icon type="ios-information-circle"></Icon>
        <span>操作确认</span>
      </p>
      <div style="text-align:center">
        <p>{{ modalTipContent }}</p>
      </div>
      <div slot="footer">
        <Button type="error" size="large" long :loading="modalLoading" @click="modalTipOk">确认操作</Button>
      </div>
    </Modal>
  </div>
</template>

<script>

import {mapGetters, mapState} from "vuex"
import axios from "axios";

export default {
  name: "File",
  computed: {
    ...mapState(["url", "host", "resourceHost", "realSideWidth","resourceTypeMap"]),
    ...mapGetters(["contentWidth", "contentHeight"]),
  },
  data() {
    return {
      btnLoading: false,
      isLoading: false,
      modalTip: false,
      modalTipContent: null,
      modalLoading: false,
      isFileAnalyseModalShow: false,
      isPageSizeChanging:false,
      modalTitle: '存储文件分析结果',
      modalTitleData: null,
      operatorType: ['存储文件分析结果','文件分析','文件清理','禁用文件','解禁文件','删除文件'],
      headers: {
        'u-projectId': null,
        'u-uid': null,
        'u-token': null,
      },
      updateForm: {
        id: null,
        userName : null,
        password : null,
        phone : null,
        nickName : null,
        address : null,
        avatarUrl : null,
        roleId : null,
        projectId : null,
      },
      fileAnalyseResult: {
        total:0,
        unused:0,
        available:0,
        usedNonExistent:0,
        category: {
          clientSoftware:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          clientLogo:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          constructionUnits:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          dangerProcess:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          valueChest:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          danger:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          user:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          pipeline:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          pileCard:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          flyTask:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
          other:{
            available:0,
            total:0,
            unused:0,
            usedNonExistent:0
          },
        }
      },
      page:{
        total: 0,
        pageSize: 10,
        pageNum: 1,
        descParams:'id'
      },
      tableColumns: [
        {
          title: '用户ID',
          key: 'id',
          width: 100,
          minWidth: 100,
          resizable: true,
          align: "center",
          ellipsis: true,
          sortable: true,
        },
        {
          title: '文件名称',
          key: 'url',
          resizable: true,
          minWidth: 180,
          align: "center",
          render: function (createElement,data){
            return createElement('Tooltip',{
              attrs: {
                content : data.row.url,
                placement : "top-start",
                style: {
                  width: '100%'
                }
              }
            },[createElement('div',data.row.url.substring(data.row.url.lastIndexOf("/")+1))]);
          }
        },
        {
          title: '文件类别',
          key: 'category',
          resizable: true,
          width: 150,
          minWidth: 100,
          align: "center",
          render: this.categoryRender
        },
        {
          title: '文件元类型',
          key: 'type',
          resizable: true,
          width: 150,
          minWidth: 100,
          align: "center"
        },
        {
          title: '文件大小',
          key: 'size',
          resizable: true,
          minWidth: 120,
          align: "center",
          render:this.fileSizeRender
        },
        {
          title: '创建时间',
          key: 'createTime',
          resizable: true,
          minWidth: 180,
          align: "center"
        },
        {
          title: '所属项目编号',
          key: 'projectId',
          resizable: true,
          width: 130,
          align: "center"
        },
        {
          title: '文件可用状态',
          key: 'state',
          resizable: true,
          width: 130,
          align: "center",
          render:function (createElement,e){
            let {state} = e.row;
            if (state === 0){
              return createElement('Tooltip',{
                attrs: {
                  content :"可用",
                  placement : "top"
                }
              },[createElement('div',{
                style: {
                  height:'15px',
                  width:'15px',
                  borderRadius:'50%',
                  background: '#1afa29'
                }
              },'')]);
            }else if (state === 1){
              return createElement('Tooltip',{
                attrs: {
                  content :"禁用",
                  placement : "top"
                }
              },[createElement('div',{
                style: {
                  height:'15px',
                  width:'15px',
                  borderRadius:'50%',
                  background: '#f74242'
                }
              },'')]);
            }
          }
        },
        {
          title: '操作',
          resizable: true,
          minWidth: 150,
          align: "center",
          render: this.operatorRenderFunction
        }
      ],
      dataList: [],
      fileAnalyseCategoryColumns: [
        {
          title: '文件类别',
          key: 'category',
          minWidth: 140,
          resizable: true,
          align: "center",
          ellipsis: true,
        },
        {
          title: '文件总数量',
          key: 'total',
          resizable: true,
          width: 140,
          align: "center",
          sortable: true,
        },
        {
          title: '文件可用数量',
          key: 'available',
          resizable: true,
          width: 140,
          align: "center",
        },
        {
          title: '无引用文件数量',
          key: 'unused',
          resizable: true,
          width: 140,
          minWidth: 100,
          align: "center"
        },
        {
          title: '在使用文件丢失数量',
          key: 'usedNonExistent',
          width: 170,
          resizable: true,
          align: "center"
        }
      ],
      fileAnalyseCategoryList: []
    }
  },
  watch: {
    fileAnalyseResult:function (e){
      this.fileAnalyseCategoryList = [];
      for (let item in e.category){
        switch (item){
          case 'clientLogo':{
            e.category[item].category = "客户端Logo";
          }break;
          case 'clientSoftware':{
            e.category[item].category = "客户端软件";
          }break;
          case 'constructionUnits':{
            e.category[item].category = "施工作业区图片";
          }break;
          case 'danger':{
            e.category[item].category = "险情图片";
          }break;
          case 'dangerProcess':{
            e.category[item].category = "险情处理图片";
          }break;
          case 'flyTask':{
            e.category[item].category = "飞行任务遥测PB";
          }break;
          case 'pileCard':{
            e.category[item].category = "桩牌图片";
          }break;
          case 'pipeline':{
            e.category[item].category = "管线PB";
          }break;
          case 'user':{
            e.category[item].category = "用户头像图片";
          }break;
          case 'valueChest':{
            e.category[item].category = "设施图片";
          }break;
          case 'other':{
            e.category[item].category = "其他文件";
          }break;
        }
        this.fileAnalyseCategoryList.push(e.category[item]);
      }
    }
  },
  created: function () {

  },
  mounted: function () {
    this.selectPageList(this.page);
  },
  methods: {
    categoryRender(createElement, data) {
      return createElement('span',this.$store.state.resourceTypeMap[data.row.category])
    },
    fileSizeRender(createElement,data){
      return createElement('span',this.flowUnitConversion(data.row.size,2));
    },
    flowUnitConversion(number,decimalPoint=2){
      let conversionFlow = 0;
      if(1024 > number){
        conversionFlow = parseInt(number)+"bit";
      }else if(1024 < number && number < (1024 * 1024)){
        conversionFlow = (number/1024).toFixed(decimalPoint)+"KB";
      }else if(number > (1024 * 1024)) {
        conversionFlow = (number/(1024*1024)).toFixed(decimalPoint)+"MB";
      }
      return conversionFlow;
    },
    onPageChange(changedPage) {
      this.page.pageNum = changedPage;
      !this.isPageSizeChanging ? this.selectPageList(this.page) : {};
    },
    onPageSizeChange(changedPageSize) {
      this.isPageSizeChanging = true;
      new Promise(resolve => {
        this.page.pageSize = changedPageSize;
        resolve(changedPageSize)
      }).then(() => {
        this.selectPageList(this.page);
        this.isPageSizeChanging = false;
      })
    },
    fileAnalyseOperator(){
      this.fileAnalyse();
    },
    fileCleanOperator(){
      this.modalTitle = this.operatorType[2];
      this.modalTipContent = "将开始执行文件清理,该操作将执行较长时间,是否确认执行?"
      this.modalTip = true;
    },
    modalTipOk() {
      this.modalLoading = true;
      switch (this.modalTitle){
        case this.operatorType[2]:{
          this.modalLoading = false;
          this.modalTip = false;
          this.fileClean();
        }break;
      }
    },
    operatorRenderFunction(createElement, data) {
      let self = this;
      let {
        id,url,projectId,state,type
      } = data.row;
      let btnList = [];
      if (type === "application/octet-stream" || type === "application/x-msdos-program"){
        btnList.push(createElement('Button', {
          'class': 'button-item',
          style: {
            width: '100px',
            border: '#5CADFF 1px dashed',
            color: '#5cadff'
          },
          attrs: {
            type: "dashed"
          },
          nativeOn: {
            click: function () {
              window.location.href = url;
            }
          },
        }, '下载'));
      }else {
        btnList.push(createElement('Button', {
          'class': 'button-item',
          style: {
            width: '100px',
            border: '#5CADFF 1px dashed',
            color: '#5cadff'
          },
          attrs: {
            type: "dashed"
          },
          nativeOn: {
            click: function () {
              window.open(url);
            }
          },
        }, '查看'));
      }
      return createElement("div", {'class': 'r-n-c-c'}, [
        createElement('ButtonGroup', btnList),
      ])
    },
    selectPageList(selectForm) {
      let self = this;
      let form = Object.assign({}, selectForm);
      axios.get(self.url.file_list, {params: form}).then(function (response) {
        let {records,total} = response.data.content;
        self.page.total = total;
        self.dataList = records;
        self.isLoading = false;
      }).catch(function () {
        self.isLoading = false;
      });
    },
    fileAnalyse(){
      let self = this;
      this.$Spin.show();
      axios.get(self.url.file_analysis).then(function (response) {
        self.$Spin.hide();
        let {message, state, content} = response.data;
        if (state === 200) {
          self.fileAnalyseResult = content;
          self.isFileAnalyseModalShow = true;
        } else {
          self.$Message.error(message);
        }
      });
    },
    fileClean(){
      let self = this;
      self.btnLoading = true;
      axios.delete(self.url.file_clean).then(function (response) {
        self.btnLoading = false;
        let {message, state, content} = response.data;
        let {unusedDbDeleteCount,unusedOssDeleteCount,usedNonExistentSetStatus} = content;
        if (state === 200) {
          self.$Message.success(message);
          self.$Notice.open({
            duration: 30,
            title: '清理结果',
            desc: '未使用DB删除记录数量[' + unusedDbDeleteCount +'] ,未使用OSS文件实际删除数量[' + unusedOssDeleteCount +'], 在使用但OSS已删除禁用数量'+usedNonExistentSetStatus+']'
          });
        } else {
          self.$Message.error(message);
        }
      });
    },
  }
}
</script>

<style scoped>
#content {
  background: #FFFFFF;
  padding: 15px;
  overflow: auto;
}

.item-input {
  height: 45px;
  line-height: 45px;
  margin-bottom: 10px;
}

.item-input-span {
  /*height: inherit;*/
  width: 120px;
}

.item-key {
  /*height: inherit;*/
  width: 150px;
}
.item-value {
  /*height: inherit;*/
  width: 50px;
}

.ivu-form-item-content {
  margin-left: 0 !important;
  position: relative;
  line-height: 32px;
  font-size: 14px;
}

.ivu-form-item {
  margin-bottom: 0;
  width: 100%;
}

.button-item {
  border: #19be6b 1px dashed;
  color: #19be6b;
}

.filter-item:first-of-type {
  margin-left: 0;
}
.filter-item {
  margin: 0 5px;
}

.demo-spin-icon-load{
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from { transform: rotate(0deg);}
  50%  { transform: rotate(180deg);}
  to   { transform: rotate(360deg);}
}
.demo-spin-col{
  height: 20px;
  position: relative;
}
</style>